<template>
<div>
  <el-button type="primary" icon="el-icon-plus"  @click="addTradeMark">添加</el-button>

  <el-table
    style="width: 100%; margin: 10px 0px"
    border
    :header-cell-style="{ color: '#409EFF' }"
    :data="records">

    <el-table-column type="index" label="序号" width="80px" align="center">
    </el-table-column>
    <el-table-column prop="tmName" label="品牌名称" width="width">
    </el-table-column>
    <el-table-column label="品牌LOGO" width="width">
      <template slot-scope="{row, $index}">
        <img :src="row.logoUrl" alt="" style="width: 80px; height: 80px" />
      </template>
    </el-table-column>

    <el-table-column prop="prop" label="操作" width="width">
      <template slot-scope="{row, $index}">
        <el-button type="warning" size="mini" icon="el-icon-edit" @click="updateTradeMark(row)"
        style="margin-right: 10px;"
        >修改</el-button
        >
        <el-popconfirm title="这是一段内容确定删除吗？" icon="el-icon-delete" icon-color="#409EFF" @onConfirm="removOne(row.id)">
        <el-button
          type="danger"
          size="mini"
          icon="el-icon-delete"
          slot="reference"
        >删除</el-button
        >
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>


  <el-pagination
    style="text-align: center"
    :current-page="page"
    :page-sizes="[3, 5, 10]"
    :page-size="limit"
    background
    prev-text="上一页"
    next-text="下一页"
    layout="prev, pager, next, jumper,->,total,sizes"
    :total="total"
    @current-change="getTrademarkList"
    @size-change="handleSizeChange"
  >
  </el-pagination>

  <el-dialog :title="tmForm.id ? '修改品牌' : '添加品牌'" :visible.sync="dialogFormVisible"
             :show-close="false"
             :before-close="close"
  >
    <!-- form在收集数据的时候需要书写model -->
    <el-form style="width: 80%" :model="tmForm" :rules="rules" ref="cur">
      <el-form-item label="品牌名称" label-width="80px" prop="tmName">
        <!-- 收集品牌的名称 -->
        <el-input autocomplete="off" v-model="tmForm.tmName"></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="logoUrl">
        <!--
          上传图片
            action前缀需要加上/dev-api，因为代理服务器工作
              el-upload上传图片，发请求用的并非axios，底层用的是form标签实现上传图片【发请求】
            show-file-list:上传图片底下是否展示文件名字
            on-success:上传成功的回调(图片上传成功执行一次)
            before-upload:上传成功之前的回调函数
         -->
        <el-upload
          class="avatar-uploader"
          action="/dev-api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="addOrUpdateTradeMark"
      >确 定</el-button
      >
    </div>
  </el-dialog>

  <el-dialog
    title="提示"
    :visible.sync="centerDialogVisible"
    width="30%"
    center>
    <span>确认删除吗</span>
    <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="removOne">确 定</el-button>
  </span>
  </el-dialog>


</div>
</template>

<script>
export default {
    name: "Trademark",
    data() {
      const validateTmName = (rule, value, callback) => {
        if (/^[\u4e00-\u9fa5]{2,10}$/.test(value)) {
          callback();
        } else {
          //不符合条件
          callback(new Error("品牌的名字是汉字2-10位"));
        }
      };
      return {
        page : 1,
        limit : 3,
        total : 0,

        //品牌的数据--数组
        records: [],

        dialogFormVisible: false,
        centerDialogVisible : false,
        //上传图片用的属性
        imageUrl: "",
        tmForm : {
          tmName : '',
          logoUrl : '',
        },
        rules : {
          tmName:[
            { required: true, message: "请输入品牌名称", trigger: "change" },
            // { min: 2, max: 10, message: "品牌的名字在2-10位", trigger: "change" },
            //自定义校验规则--常用的
            //validator:用来设置自定义校验规则地方
            { validator: validateTmName, trigger: "change" },
          ],
          logoUrl : [
            { required: true, message: "请选择品牌LOGO" }
          ]
        },
        // title : '添加品牌',
        removeId : 0,
      }
    },

    mounted() {
      this.getTrademarkList();
    },
    methods:{
      async getTrademarkList(pager = 1){
        this.page = pager;
        const {page, limit} = this;
        let res = await this.$ajax.trademark.reqTrademarkList(page, limit);
        if (res.code == 200) {
          this.records = res.data.records;
          this.total = res.data.total;
        }
      },
      handleSizeChange(limit) {
          this.limit = limit;
          this.getTrademarkList();
      },
      addTradeMark() {
        this.dialogFormVisible = true;
        this.tmForm = {
          tmName: "",
          logoUrl: "",
        };
      },
      handleAvatarSuccess(res, limit) {
        this.tmForm.logoUrl = res.data;
      },
      //图片上传之前的回调
      beforeAvatarUpload(file) {
        //判断上传图片图片类型
        const isJPG = file.type === "image/jpeg";
        //判断上传图图片的大小
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error("上传头像图片只能是 JPG 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
        }
        return isJPG && isLt2M;
      },

      async addOrUpdateTradeMark() {
        this.dialogFormVisible = false;
        try{
          //添加或者修改品牌成功
          await this.$ajax.trademark.reqAddOrUpdateTrademark(this.tmForm);
          //弹出提示信息
          this.$message({
            type:'success',
            message:this.tmForm.id?'修改成功':'添加成功'
          });
          //再次获取品牌数据进行最新数据的展示
          this.getTrademarkList(this.tmForm.id ? this.page : 1);

        } catch(e) {
          this.$message({
            type : 'danger',
            message:this.tmForm.id?'修改失败':'添加失败'
          })
        }
      },

      // 更新
      async updateTradeMark(row) {
        this.dialogFormVisible = true;
        this.tmForm = {...row};
      },
      cancel() {
        this.dialogFormVisible = false;
        this.$refs.cur.resetFields();
      },
      close() {

      },

      async removOne(id) {
        try {
          let res = await this.$ajax.trademark.reqRemoveTrademark(id);
          if(res.code == 200) {
            this.getTrademarkList(
              this.records.length > 1 ? this.page : this.page - 1
            );
          }
        } catch(e) {
          this.$message({
            type : 'error',
            message:'操作失败，请重试'
          })
        }
      }
    }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
